/**
 * 上传头像
 */
import {
	request,
	base_api
} from '@/api/request/index.js'
import local_userinfo from '@/util/user/local-userinfo.js'

function updateMyheadimg(user = {}, logout = false, callback) {
	uni.showLoading({
		mask: true
	})
	request.get({
		data: {
			c: 'UserController',
			m: 'updateUserinfo',
			headimgpath: user.headimg,
			sessionid: user.sessionid,
			logout: logout
		}
	}).then(res => {
		if (res.Status == "ok") {
			local_userinfo.setUserinfo(user)
			if (callback) callback(user.headimg)
		} else {
			uni.showModal({
				content: res.Msg,
				showCancel: false
			})
		}
	}).catch(error => {
		uni.showModal({
			content: '上传失败，请稍候重试',
			showCancel: false
		})
	})
}
export default {
	//上传头像
	uploadImage(user = {}, callback) {
		uni.chooseImage({
			sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album'], //从相册选择
			count: 1,
			success(chooseimgRes) {
				
				let tempFilePath = chooseimgRes.tempFilePaths;
				let tempFiles =chooseimgRes.tempFiles[0];
				
				if(tempFiles.size > 1000*1024)
				{
					uni.showModal({
						showCancel:false,
						content:"图片太大，不能超过1M，请先压缩图片"
					})
					return;
				}
				let uploadTask = uni.uploadFile({
					url: base_api + 'upload.ashx',
					filePath: tempFilePath[0],
					name: 'file',
					success(uploadFileRes) {
						let result = uploadFileRes.data;
						result = result ? JSON.parse(result) : {};
						if (result.Status === 'ok') {
							let newheadimgurl = result.Tag
							user.headimg = newheadimgurl
							//更新我的头像 更新本地缓存
							updateMyheadimg(user, false, callback)
						}
					},
					fail(e) {
						uni.showModal({
							content: '上传失败，请稍候重试' + JSON.stringify(e),
							showCancel: false
						})
					},
					complete() {
						uni.hideLoading()
					}
				})
				
				uploadTask.onProgressUpdate((res) => {
					uni.showLoading({
						title: `已上传:${res.progress}%`
					})
				
					// 测试条件，取消上传任务。
					if (res.progress >= 100) {
						uni.hideLoading()
					}
				});
			}
		})
	}
}
